package com.airforce.controller;


import com.airforce.mappers.index_awardMapper;
import com.airforce.mappers.servicesMapper;
import com.airforce.mappers.user_awardMapper;
import com.airforce.mappers.wechat_userMapper;
import com.airforce.model.index_award;
import com.airforce.model.user_award;
import com.airforce.utils.JsonUtil;
import com.airforce.utils.MD5BASE64Util;
import com.airforce.utils.ResultCode;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.airforce.service.DrawLotteryUtil.drawGift;

@RestController
@RequestMapping(value = "index")
public class Index_awardControl {

    @Autowired
    index_awardMapper index_awardMapper;


    @Autowired
    user_awardMapper user_awardMapper;

    @Autowired
    servicesMapper servicesMapper;

    @Autowired
    wechat_userMapper wechat_userMapper;
    private final static Logger logger = LoggerFactory.getLogger(Index_awardControl.class);


    @GetMapping(value = "/app/isLottery")
    public Object isLottery(@RequestParam String token){
        String[] str = MD5BASE64Util.base64decode(token).split(",");
        String openid = str[1];
        int num=wechat_userMapper.selectByopenid(openid).getLotterynum();
        if(num>0){
            return ResultCode.SUCCESS.result();
        }else {
            return ResultCode.NO_LOOTNUM.result();
        }
    }



    //抽奖 并加入奖品
    @GetMapping(value = "app/DrawLottery")
    public Object appDrawLottery(@RequestParam String token) {
            String[] str = MD5BASE64Util.base64decode(token).split(",");
            String openid = str[1];
            String before=null;  //分享前必中奖品
            String after=null;//分享后必中奖品
            String other=null;//不分前后
            List<index_award> list = index_awardMapper.selectByall();
            //判断分享前后
            byte share = wechat_userMapper.selectByopenid(openid).getShare();
        List<Map<String,Object>> useraward=user_awardMapper.selectByuseraward(openid);


        for(int j=0;j<useraward.size();j++){
            if(Integer.parseInt(useraward.get(j).get("flag").toString())==1&&Integer.parseInt(useraward.get(j).get("sharebefore").toString())==0){
                    before=  useraward.get(j).get("awardname").toString();
                }else if(Integer.parseInt(useraward.get(j).get("flag").toString())==1&&Integer.parseInt(useraward.get(j).get("sharebefore").toString())==1){
                    after=useraward.get(j).get("awardname").toString();

            }else if(Integer.parseInt(useraward.get(j).get("flag").toString())==1&&Integer.parseInt(useraward.get(j).get("sharebefore").toString())==2){
                other=useraward.get(j).get("awardname").toString();
            }else  if(Integer.parseInt(useraward.get(j).get("flag").toString())==0&&Integer.parseInt(useraward.get(j).get("sharebefore").toString())==0){
                before=  useraward.get(j).get("awardname").toString();
            }else if(Integer.parseInt(useraward.get(j).get("flag").toString())==0&&Integer.parseInt(useraward.get(j).get("sharebefore").toString())==1){
                after=useraward.get(j).get("awardname").toString();

            }else if(Integer.parseInt(useraward.get(j).get("flag").toString())==0&&Integer.parseInt(useraward.get(j).get("sharebefore").toString())==2){
                other=useraward.get(j).get("awardname").toString();
            }
        }

            if (share == 0 ) {
                logger.info(openid+"进行了抽取分享前奖品");
                for(int i=0;i<list.size();i++){
                    //修改概率
                    if (list.get(i).getSharebefore() == 1 ){
                        list.get(i).setPower(0.0D);
                    }
                }

                //判断是否已经中奖
                if(before==null){
                    if(wechat_userMapper.selectByopenid(openid).getLotterynum()==1){
                   //     System.out.println("第二次必抽中，修改概率");
                        for(int k=0;k<list.size();k++){
                            if(list.get(k).getFlag()==1&&list.get(k).getSharebefore()==0
                                    ){
                                list.get(k).setPower(1.0D);
                            }
                        }
                    }

                }
                else if(useraward!=null) {

                      //  System.out.println("已经抽中，修改概率");
                        for (int k = 0; k < list.size(); k++) {
                            if (list.get(k).getAwardname().equals("谢谢参与")  || list.get(k).getId() == 6) {
                                list.get(k).setPower(1.0D);
                            } else {
                                list.get(k).setPower(0.0D);
                            }
                        }

                }
//                System.out.println("当前LIST为："+JsonUtil.toJson(list));

//                list = index_awardMapper.selectByBefore();
            } else if (share == 1) {
                logger.info(openid+"进行了抽取分享后奖品");

                for(int i=0;i<list.size();i++){
                    if (list.get(i).getSharebefore() == 0){
                        list.get(i).setPower(0.0D);
                    }
                }
                if(after==null){

//                        logger.info("第二次必抽中，修改概率");
                        for(int k=0;k<list.size();k++){
                            if(list.get(k).getFlag()==1&&list.get(k).getSharebefore()==1){
                                list.get(k).setPower(1.0D);
                            }

                    }
                }
                else if(useraward!=null) {


                        for (int k = 0; k < list.size(); k++) {
                            if (list.get(k).getAwardname().equals("谢谢参与")  || list.get(k).getId() == 6) {
                                list.get(k).setPower(1.0D);
                            } else {
                                list.get(k).setPower(0.0D);
                            }
                        }

                }


            }
//        System.out.println("当前LIST为："+JsonUtil.toJson(list));
            int index = drawGift(list);
            Map<String, Object> map = new HashMap<>();
//            System.out.println("奖品索引为" + index);
            map.put("index", index);
            map.put("id", list.get(index).getId());
            map.put("awardname", list.get(index).getAwardname());
//            map.put("awardname", list.get(index).getAwardname());
//            map.put("awardprice", list.get(index).getAwardprice());
            //减少抽奖次数
            wechat_userMapper.updataBynumreduce(openid);
            logger.info(openid+"抽奖次数减少");
            //写入奖品信息
            if (!list.get(index).getAwardname().equals("谢谢参与") || list.get(index).getId() != 6) {
                user_award user = new user_award();
                user.setAwardid(list.get(index).getId());
                user.setOpenid(openid);
                user_award user_parm = user_awardMapper.selectByid(user);
                if (user_parm != null) {
                    logger.info("奖品相同进行更新数量");
                    user.setId(user_parm.getId());
                    user.setNumber(user_parm.getNumber() + 1);
                    user_awardMapper.updateByPrimaryKeySelective(user);
                } else {
                    user_awardMapper.insertSelective(user);
                    logger.info("添加用户奖品");
                }
//                System.out.println("奖品为:" + JsonUtil.toJson(list.get(index)));
                return ResultCode.SUCCESS.result(map);
            } else {
                return ResultCode.NO_PARM.result(map);
            }


    }


    //获取当前奖品信息
    @GetMapping(value = "app/useraward")
    public Object useraward(@RequestParam String token,@RequestParam Integer id){

        index_award index_award=index_awardMapper.selectByPrimaryKey(id);  //获取指定商品信息
        String[] str = MD5BASE64Util.base64decode(token).split(",");
        String openid=str[1];
        String servicesname=wechat_userMapper.selectByopenid(openid).getServicesname();
        Map<String,Object> map=new HashMap<>();
        map.put("awardname",index_award.getAwardname());
        map.put("awardimg",index_award.getAwardimg());
        map.put("awardprice",index_award.getAwardprice());
       map.put("servicesname",servicesname);
//       map.put("code",services.get(index).getCode());
        return ResultCode.SUCCESS.result(map);

    }


    //查询用户所有奖品
    @GetMapping(value = "app/userawardlist")
    public Object userawardlist(@RequestParam String token)throws NullPointerException{



        String[] str = MD5BASE64Util.base64decode(token).split(",");
        String openid = str[1];
        List<Map<String, Object>> list = user_awardMapper.selectByuseraward(openid);
        String name = wechat_userMapper.selectByopenid(openid).getServicesname();

        return ResultCode.SUCCESS.result(list, name);


    }


    //查询获奖名单
    @GetMapping(value = "app/awardall")
    public Object awardall(){

        PageHelper.startPage(10,100);
        List<Map<String,Object>> list=user_awardMapper.selectByuseraward_admin();
        List<Map<String,String>> list1=new ArrayList<>();
        List<Map<String,String>> list2=new ArrayList<>();
        Map<String,  List<Map<String,String>>>map=new HashMap<>();

        //获取奖品列表
        List<index_award> Award_list = index_awardMapper.selectByall();

        //配置奖品概率
        for(index_award item:Award_list){
            if(item.getId()==2){
                item.setPower(0.10);
            }else if(item.getId()==1||item.getId()==8){
                item.setPower(0.65);
            }else if(item.getId()==6){
                item.setPower(0.0);
            }else {
                item.setPower(0.30);
            }
        }

        //生成数据
        for(int i=0;i<list.size();i++){
            Map<String,String> tem_map=new HashMap<>();
            //随机生成奖品
           int index= drawGift(Award_list);
           String awardname=Award_list.get(index).getAwardname();

//            tem_map.put("title","恭喜用户“"+java.net.URLDecoder.decode((String) list.get(i).get("name"))+"”，获得奖品“"+list.get(i).get("awardname")+"”"+list.get(i).get("number")+"份");
            tem_map.put("title","恭喜用户“"+java.net.URLDecoder.decode((String) list.get(i).get("name"))+"”，获得奖品“"+awardname+"”"+"1份");
            tem_map.put("url","url");
            if(i>=0&&i<50){
                list1.add(tem_map);
            }else {
                list2.add(tem_map);
            }

        }
        map.put("list1",list1);
        map.put("list2",list2);
        return ResultCode.SUCCESS.result(map);

    }





//查询所有奖品
    @GetMapping(value = "app/list")
    public Object applist(){

        List<index_award> list=index_awardMapper.selectByall();

        return ResultCode.SUCCESS.result(list);
    }




   //添加奖品
    @PostMapping(value = "addpro")
    public Object addpro(@RequestBody index_award product){

        if(product!=null){

            Double power=product.getPower();
            product.setPower(power/100);

            index_awardMapper.insertSelective(product);

        }else {
            return ResultCode.NO_PARM.result();
        }
        return ResultCode.SUCCESS.result();
    }


    /**
     * 奖品查询
     * @param productname
     * @param createtime
     * @param index
     * @param num
     * @return
     */
    @GetMapping(value = "productlist")
    public Object puductlist(@RequestParam(required = false) String productname,
                             @RequestParam(required = false) String createtime,
                             @RequestParam(required = false) Integer  index,
                             @RequestParam(required = false) Integer num){

        List<index_award> list;
        if(productname!=null){

            list=index_awardMapper.selectByname("%"+productname+"%");
        }else {
            int pageTotal=index_awardMapper.selectByall().size();
            PageHelper.startPage(index,num);
            list = index_awardMapper.selectByall();
            return ResultCode.SUCCESS.result(list,pageTotal);
        }
            return ResultCode.SUCCESS.result(list);
    }


    
    @GetMapping(value="findpro")
    public Object product(@RequestParam Integer id){

        index_award list;

        if(id!=null) {
            list=index_awardMapper.selectByPrimaryKey(id);

        }else {
            return ResultCode.Empty_Selct.result();
        }
        return ResultCode.SUCCESS.result(list);
    }

    //删除商品
    @GetMapping(value = "del")
    public Object delProduct(@RequestParam Integer id){

        if(id!=null){
            index_awardMapper.deleteByPrimaryKey(id);
            logger.info("商品删除成功");
        }else {
            return ResultCode.NO_PARM.result();
        }
        return ResultCode.SUCCESS.result();
    }


    //更新商品信息

    @PostMapping(value = "reditpro")
    public Object reditpro(@RequestBody index_award product){

        if(product!=null){
            logger.info("进行商品数据更新"+product.getAwardimg());

            index_awardMapper.updateByPrimaryKeySelective(product);
            return ResultCode.SUCCESS.result();

        }else {
            return ResultCode.NO_PARM.result();
        }



    }




}


